package org.message
{
	import flash.events.EventDispatcher;
	
	import mx.messaging.Channel;
	import mx.messaging.ChannelSet;
	import mx.messaging.channels.AMFChannel;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.InvokeEvent;
	import mx.rpc.remoting.mxml.Operation;
	import mx.rpc.remoting.mxml.RemoteObject;
	
	import org.tools.ui.event.ManagerEvent;

	[Event(name="invoke",type="org.tools.ui.event.ManagerEvent")]
	[Event(name="fault", type="org.tools.ui.event.ManagerEvent")]
	public class MessageManager extends EventDispatcher
	{

		private var remote:RemoteObject=new RemoteObject();
//		private static var chachOperation:Object = new Object();

		public function MessageManager(path:String='..', destination:String='messageAction')
		{
			var cs:ChannelSet = new ChannelSet();
			var myAMF:Channel = new AMFChannel("my-amf", path + "/messagebroker/amf"); 
			cs.addChannel(myAMF);
			remote.channelSet = cs;
			
			remote.destination = destination;
			remote.showBusyCursor = true;
			remote.addEventListener(InvokeEvent.INVOKE, invokeHandler);
			remote.addEventListener(FaultEvent.FAULT, faultHandler);

		}
		
		public function get getRemote():RemoteObject{
			return this.remote;
		}

		public function getOperation(methodName:String):Operation{
			if(null==methodName || ''==methodName){
				throw new Error('远程调用方法为空！');
			}
			
			return remote[methodName];
		}
		
		private function invokeHandler(event:InvokeEvent):void{
			var invokeEvent:ManagerEvent = new ManagerEvent(ManagerEvent.INVOKE);
			this.dispatchEvent(invokeEvent);
		}
		
		private function faultHandler(event:FaultEvent):void{
			var resultEvent:ManagerEvent = new ManagerEvent(ManagerEvent.FAULT);
			resultEvent.message = event.message;

			this.dispatchEvent(resultEvent);
		}
		
	}
}
